<?php
namespace TPH\Model;
use Think\Model;
use Extend\Page;

class ChanPinGiftModel extends Model{
    protected $connection = 'DB_MG_CHANPIN';

    protected $tableName = 'gift'; 

    protected $tablePrefix = 'cms01_'; 

    const PAGESIZE_INDEX = 15;

    public function getList($cond) {
        $order = isset($cond['sort']) ? $cond['sort'] : 'gift_id desc';
        $page = isset($cond['page']) ? (int)$cond['page'] : 1;
        $pagesize = self::PAGESIZE_INDEX;

        $cond['game_id'] && $where['gift_game'] = $cond['game_id'];
        $cond['gift_type_19196'] && $where['gift_type_19196'] = $cond['gift_type_19196'];       
        $cond['gift_name'] && $where['gift_name'] = ['like', '%'.$cond['gift_name'].'%'];
        if(!empty($cond['is_expired']) && is_numeric($cond['is_expired'])){
            $datetime=date('Y-m-d H:i:s');
            if($cond['is_expired']==1){
               $where['gift_etime'] = array('lt',$datetime);
            }elseif($cond['is_expired']==2){
               $where['gift_etime'] = array('gt',$datetime);
            }
        }


        $total = $this->where($where)->count();

        $data = [];
        if($total){
            $currentrows = ($page-1)*$pagesize;
            $data = $this->where($where)->field('*')->order($order)->limit($currentrows, $pagesize)->select();
        }

        $Page = new Page($total, $pagesize);
        $show = $Page->show();
        return [$data, $show];
    }

    public function getIdName() {
        return $this->order('gift_id desc')->getField('gift_id,gift_name');
    }

    public function getGiftSelect() {
        $gift_list_temp_arr=$this->getIdName();
        $gift_list_arr=count($gift_list_temp_arr) && is_array($gift_list_temp_arr)?$gift_list_temp_arr:array();
        $games = ['请选择'] + $gift_list_arr;
        return $games;
    }

    public function upGiftNum($giftId) {
        $numAll = D('ChanPinGiftKey')->getNumAll($giftId);
        $numGet = D('ChanPinGiftKey')->getNumGet($giftId);
        $data = [
            'gift_total' => $numAll,
            'gift_number' => $numGet>$numAll?0:$numAll-$numGet
        ];
        return $this->where(['gift_id'=>$giftId])->save($data);
    }




    /**
     *获取单个礼包
     */
    public function getOneGift($gift_id){ 
        return $this->where(array('gift_id'=>$gift_id))->find();
    }



    /**
     * 修改
     * @param type $id
     * @param array $data
     * @return
     */
    public function updateById($gift_id, array $data)
    {
        return $this->where(array('gift_id'=>intval($gift_id)))->save($data);
    }



    
}